// 图片数据
const setImages = [
    {
        id: 'cat2',
        url: '/chat-background/photo-1543852786-1cf6624b9987.jpg',
        name: '猫咪2',
        description: '好奇的黑白猫探索环境'
    },
    {
        id: 'nature1',
        url: '/chat-background/photo-1501854140801-50d01698950b.jpg',
        name: '自然风景1',
        description: '宁静的山谷与河流'
    },
    {
        id: 'nature2',
        url: '/chat-background/photo-1441974231531-c6227db76b6e.jpg',
        name: '自然风景2',
        description: '迷雾森林的神秘景色'
    },
    {
        id: 'city',
        url: '/chat-background/photo-1477959858617-67f85cf4f1df.jpg',
        name: '城市风光',
        description: '现代都市天际线'
    }
];

// DOM元素
const setStackedSelector = document.getElementById('setStackedSelector');
const setBlurRange = document.getElementById('setBlurRange');
const setBlurValue = document.getElementById('setBlurValue');
const setRandomBtn = document.getElementById('setRandomBtn');
const setApplyBtn = document.getElementById('setApplyBtn');
const setResetBtn = document.getElementById('setResetBtn');
const setCurrentImage = document.getElementById('setCurrentImage');
const setCover = document.querySelector('.set-cover');
const setPreviewImage = document.querySelector('.set-preview-image');
const setFileInput = document.getElementById('setFileInput');
const cover = document.querySelector('.cover');

function initImages() {

    let img = {
        id: 'cat1',
        url: '/chat-background/' + localStorage.getItem("backgroundUrl"),
        name: 'eeee',
        description: 'eeee'
    };
    setImages.push(img);
}

initImages();
// 初始化堆叠式选择器
function initSetStackedSelector() {
    setImages.forEach(img => {
        createImageOption(img);
    });
}

// 创建图片选项
function createImageOption(img) {
    const option = document.createElement('div');
    option.className = 'set-stacked-option';
    option.dataset.id = img.id;
    option.dataset.url = img.url;
    option.dataset.name = img.name;

    const thumb = document.createElement('div');
    thumb.className = 'set-stacked-thumb';

    const imgEl = document.createElement('img');
    imgEl.src = img.url;
    imgEl.alt = img.name;

    thumb.appendChild(imgEl);

    const info = document.createElement('div');
    info.className = 'set-stacked-info';

    const title = document.createElement('h3');
    title.textContent = img.name;

    const desc = document.createElement('p');
    desc.textContent = img.description;

    info.appendChild(title);
    info.appendChild(desc);

    option.appendChild(thumb);
    option.appendChild(info);
    setStackedSelector.appendChild(option);

    // 设置第一个为默认选中
    if (img.id === 'cat1') {
        option.classList.add('active');
        setCurrentImage.textContent = img.name;
    }


    // 添加点击事件
    option.addEventListener('click', () => {
        // 更新选中状态
        document.querySelectorAll('.set-stacked-option').forEach(opt => {
            opt.classList.remove('active');
        });
        option.classList.add('active');

        // 更改背景预览
        changeSetBackground(img.url, img.name);
    });
}


// 切换背景图片
function changeSetBackground(imageUrl, imageName) {
    // 更新预览图
    setPreviewImage.style.backgroundImage = `url('${imageUrl}')`;

    setCover.style.backgroundImage = `url('${imageUrl}')`;

    setCurrentImage.textContent = imageName;
}

let readImageUrl = null;
// 应用背景设置
function applySetBackground() {
    const activeOption = document.querySelector('.set-stacked-option.active');
    if (activeOption) {
        const tmp = activeOption.dataset.url;

        let imageUrl = tmp.replace("/chat-background/", "");

        //保存到后端
        $.ajax({
            url: "set/set-background",
            type: "post",
            contentType: "application/json",
            data: JSON.stringify({
                userId: localStorage.getItem("userId"),
                blur: blurValue,
                backgroundUrl: imageUrl,
                imageUrlBase64: readImageUrl
            }),
            success: function (result) {
                let data = result.data;
                if (data.status == "fail") {
                    setShowNotification(data.msg, "error");
                    return;
                }
                cover.style.backgroundImage = `url('${"/chat-background/" + data.imgUrl}')`;
                cover.style.filter = `blur(${blurValue}px)`;

                changeSetBackground(data.imgUrl, "using")
                if (readImageUrl != null) {
                    activeOption.setAttribute("data-url", "/chat-background/" + data.imgUrl);
                    readImageUrl = null;
                }
                setShowNotification("设置成功")
            },

            error: function (err) {
                if (err.status == 406) {
                    location.href = "login.html";
                    return;
                }
                console.log(result.message);
            }
        });
    }
}

// 更新模糊效果
function updateSetBlur(value) {
    setCover.style.filter = `blur(${value}px)`;
    setBlurValue.textContent = `${value}px`;
}

// 随机选择背景
function getRandomSetImage() {
    const randomIndex = Math.floor(Math.random() * setImages.length);
    return setImages[randomIndex];
}

// 处理文件上传
function handleFileUpload(file) {
    const reader = new FileReader();

    reader.onload = function (e) {
        readImageUrl = e.target.result;

        // 创建新的图片选项
        const newImage = {
            id: 'custom_' + Date.now(),
            url: readImageUrl,
            name: '自定义图片',
            description: '您上传的图片'
        };

        // 添加到图片数组
        setImages.push(newImage);

        // 创建UI选项
        createImageOption(newImage);

        // 选中新上传的图片
        const lastOption = setStackedSelector.lastChild;
        lastOption.classList.add('active');

        // 移除其他选项的选中状态
        document.querySelectorAll('.set-stacked-option').forEach(opt => {
            if (opt !== lastOption) {
                opt.classList.remove('active');
            }
        });

        // 应用新图片
        changeSetBackground(readImageUrl, '自定义图片');
    };

    reader.readAsDataURL(file);
}

let blurValue = 20;

// 事件监听
setBlurRange.addEventListener('input', () => {
    blurValue = setBlurRange.value;
    updateSetBlur(setBlurRange.value);
});

setRandomBtn.addEventListener('click', () => {
    const randomImg = getRandomSetImage();
    changeSetBackground(randomImg.url, randomImg.name);

    // 更新选中状态
    document.querySelectorAll('.set-stacked-option').forEach(opt => {
        opt.classList.remove('active');
        if (opt.dataset.id === randomImg.id) {
            opt.classList.add('active');
            // 滚动到选中的选项
            opt.scrollIntoView({behavior: 'smooth', block: 'nearest'});
        }
    });
});

setApplyBtn.addEventListener('click', applySetBackground);

setResetBtn.addEventListener('click', () => {
    // 重置为默认图片
    const defaultImg = setImages[0];
    changeSetBackground(defaultImg.url, defaultImg.name);

    // 重置选中状态
    document.querySelectorAll('.set-stacked-option').forEach(opt => {
        opt.classList.remove('active');
        if (opt.dataset.id === defaultImg.id) {
            opt.classList.add('active');
            // 滚动到顶部
            setStackedSelector.scrollTop = 0;
        }
    });

    // 重置模糊
    setBlurRange.value = 20;
    updateSetBlur(20);
});

setFileInput.addEventListener('change', (e) => {
    const file = e.target.files[0];
    if (file) {
        // 检查文件类型
        if (!file.type.match('image.*')) {
            alert('请选择有效的图片文件！');
            return;
        }

        // 检查文件大小 (限制为5MB)
        if (file.size > 5 * 1024 * 1024) {
            alert('图片大小不能超过5MB！');
            return;
        }

        handleFileUpload(file);
    }

    // 重置文件输入
    setFileInput.value = '';
});

// 初始化页面
window.addEventListener('DOMContentLoaded', () => {
    initSetStackedSelector();
    updateSetBlur(20);
});
